/**
 * 
 */
package com.fangqk.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fangqk.entity.Link;
import com.fangqk.entity.LoginTrace;
import com.fangqk.entity.User;
import com.fangqk.service.LinkService;
import com.fangqk.service.LoginTraceService;
import com.fangqk.service.UserService;
import com.fangqk.utils.IpUtils;
import com.fangqk.utils.MD5;
import com.fangqk.utils.Ret;
import com.fangqk.utils.redis.RedisUtils;

/**
 * @author G-Train
 *
 */
@Controller
@RequestMapping("/nav/user")
public class UserController {

	@Autowired
	UserService userServiceImpl;
	@Autowired
	LinkService linkServiceImpl;
	@Autowired
	LoginTraceService loginTraceServiceImpl;
	@Autowired
	RedisUtils redisUtils;

	/**
	 * 用户注册、信息修改
	 */
	@RequestMapping("register")
	@ResponseBody
	public Ret register(HttpServletRequest request, HttpServletResponse response, User user, Integer regist,
			@RequestParam(value = "oldPwd", required = false) String oldPwd) {
		if (null == user || null == user.getUserName() || null == user.getPassword()) {
			return new Ret(Ret.FAIL, "请填写完整的注册信息", null);
		}
		User u = userServiceImpl.selectByUserName(user.getUserName());

		if (regist > 0) {
			user.setPassword(MD5.getMD5(user.getPassword()));
			user.setCreateTime(new Date());
			int insert = userServiceImpl.insertUser(user);
			if (insert == 1) {
				return new Ret(Ret.SUCCESS, "注册成功！", null);
			} else {
				return new Ret(Ret.FAIL, "注册失败！", null);
			}
		} else {
			if (!StringUtils.isEmpty(user.getNickName())) {
				u.setNickName(user.getNickName());
			}
			if (u.getPassword().equals(MD5.getMD5(oldPwd))) {
				if (!StringUtils.isEmpty(user.getPassword())) {
					u.setPassword(MD5.getMD5(user.getPassword()));
				}
			}
			u.setUpdateTime(new Date());
			int update = userServiceImpl.updateByPrimaryKeySelective(u);
			if (update == 1) {
				return new Ret(Ret.SUCCESS, "修改成功！", null);
			}
			return new Ret(Ret.FAIL, "修改失败！", null);
		}
	}

	@RequestMapping("/login")
	@ResponseBody
	public Ret login(HttpServletRequest request, HttpServletResponse response, User user) {
		User u = userServiceImpl.selectByUserName(user.getUserName());
		if (null != u && u.getPassword().equals(MD5.getMD5(user.getPassword()))) {
			Map<String, Object> map = new HashMap<>();
			String links = (String) redisUtils.get(u.getUserId() + "_link");
			if (null == links) {
				Link link = linkServiceImpl.getOneByUserId(u.getUserId());
				if (link != null) {
					links = link.getLinks();
					redisUtils.set(u.getUserId() + "_link", links);
				}
			}
			if (links != null) {
				map.put("links", links);
			}
			LoginTrace trace = new LoginTrace();
			trace.setCreateTime(new Date());
			trace.setUserId(u.getUserId());
			trace.setIp(IpUtils.getIpAddr(request));
			loginTraceServiceImpl.insert(trace);

			map.put("user", u);
			String token = UUID.randomUUID().toString().replaceAll("-", "");
			redisUtils.set(u.getUserName() + "_token", token);
			map.put("token", token);
			return new Ret(Ret.SUCCESS, "登录成功！", map);
		}
		return new Ret(Ret.FAIL, "账号或密码不正确，登录失败！", null);
	}

	@RequestMapping("/hasLogin")
	@ResponseBody
	public Ret hasLogin(String token, String userName) {
		String tokenInRedis = (String) redisUtils.get(userName + "_token");
		if (token.equals(tokenInRedis)) {
			return new Ret(Ret.SUCCESS, "用户登录信息存在", null);
		}
		return new Ret(Ret.FAIL, "用户未登录", null);
	}

	@RequestMapping("/logout")
	@ResponseBody
	public Ret logout(HttpSession session, User user) {
		if (redisUtils.exists(user.getUserName() + "_token")) {
			redisUtils.remove(user.getUserName() + "_token");
		}
		if (redisUtils.exists(user.getUserId() + "_link")) {
			redisUtils.remove(user.getUserId() + "_link");
		}
		return new Ret(Ret.SUCCESS, "退出成功！", null);
	}

}
